package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author shkstart
 * @create 2023-02-17-14:19
 */
@Slf4j
@Controller
@ResponseBody

@RestController

//当前方法返回一个非静态页面的数据
@RequestMapping("/user")
public class UserController {

    //定义全局的session key
    private final String SESSION_KEY = "SESSION_KEY";
    /*
    得到session*/
    @RequestMapping("/setsess")
    public Boolean setSession(HttpServletRequest request){
        boolean result = false;
        //1.得到session对象
        try{
            HttpSession session = request.getSession(true);
            session.setAttribute(SESSION_KEY, "java");
            result = true;
        }catch (Exception e){
            log.info("出现了异常"+e.getMessage());
        }
        return result;
    }


    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(required =false,
            name = "SESSION_KEY")String data){
            return data;
    }
    @RequestMapping("/getsess")//获取session方式一
    public String getSession(HttpServletRequest request){
        String result = "";
        //1.得到session,如果存在就查询session中的值，否则返回空

        //false表示 如果没有session对象，就不用创建session对象
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute(SESSION_KEY)!=null){
            result = (String) session.getAttribute(SESSION_KEY);
        }
        return result;
    }


    /*
    获取请求头的方式
     */
    @RequestMapping("/getua")
    public String getUA(@RequestHeader("User-Agent")String userAgent){
        return userAgent;
    }


    /*
    获取cookie方式2
     */
    @RequestMapping("/getcook2")
    public String  getCooke(@CookieValue("ah")String str){
        return str;
    }

    @RequestMapping("/getcookie")
    public void getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        log.info("cook length:"+cookies.length);
        Arrays.stream(cookies).forEach(cookie->{
            log.info(cookie.getName()+":"+cookie.getValue());
        });
    }

    @Value("${myfile.path}")
    private String filePath;//从配置文件中获取路径
    /*
    上传文件
     */
    @RequestMapping("/upfile")
    public boolean upFile(String name, @RequestPart("userfile")MultipartFile file){
        boolean result = false;
        try{
            //得到原文件的名称和后缀
            String fileType = file.getOriginalFilename();
            fileType = fileType.substring(fileType.lastIndexOf("."));

            //文件名称的保存
            String fileName = UUID.randomUUID().toString()+fileType;
            file.transferTo(new File(filePath+fileName));
            result = true;
            log.info(name + ":上传图片成功");
        } catch (IOException e) {
            System.out.println("上传失败");
        }
        return result;
    }

    @RequestMapping("/hero/{name}/{id}")
    public String herName(@PathVariable String name,
                          @PathVariable Integer id){
        return name+"id:"+id;
    }

    @RequestMapping("/reg")
    public UserInfo reg(@RequestBody UserInfo userInfo){
        return userInfo;
    }


    @RequestMapping("/login")
    public boolean islogin(String name,String password){
        boolean result = false;
        if(StringUtils.hasLength(name)&&
                StringUtils.hasLength(password)&&
                name.equals("admin")&&
                        password.equals("admin"))   {
            result = true;
        }
        return result;
    }

    /**
     * 接受单个参数
     * @param name
     * @return
     */
    @RequestMapping("/showname")
    public String showName(String name){
        return "展示姓名"+name;
    }

    @RequestMapping(value= "/sayhi",method= RequestMethod.GET)
    public String sayHi(){
        return  "Hello,MVC";
    }


    @GetMapping("/sayhe")
    public String sayHi2(){
        return "hihi,MVC78979879";
    }


    @PostMapping("/sayho")
    public String sayHi3(){
        return "Hello,MVC3";
    }

}
